using System;
using System.Collections.Generic;
using System.Linq;

namespace BSDS.Commands.Commands.Creation
{
    public class CommandFactory
    {
        private readonly List<ICommandCreator> creators;

        public CommandFactory(List<ICommandCreator> creators)
        {
            this.creators = creators;
        }

        public ICommand Create(Dictionary<string, string> parameters)
        {
            ICommand command = null;

            if (creators.Any(creator => creator.TryCreate(parameters, out command)))
            {
                return command;
            }

            return null;
        }

        public void OverrideCommandCreator(Type overridenType, ICommandCreator newCreator)
        {
            for (int i = creators.Count - 1; i >= 0; i--)
            {
                if(creators[i].GetType() == overridenType)
                {
                    creators.RemoveAt(i);
                }
            }

            creators.Insert(0, newCreator);
        }
    }
}